import React from 'react';
import styles from './index.less';
import { Button, DatePicker, Select, Space, Spin, Table } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { tableLocale } from '@/tool/components/PageEmpty';
import { TRMessage } from '#/components';
import { UploadOutlined, UpSquareOutlined, DownSquareOutlined } from '#/utils/antdIcons';
import { useTRState } from '#/utils/trHooks';
import { export_json_to_excel } from '@/utils/fileExport';
import { TjSegmented, TjChart } from '@/pages/ETrade/components';

import { queryNodePriceDistributionStatistics } from '../../services';
import { fmtDataSource } from './helper';
import { useThemeChange } from '@/hooks';

const getDateRange = () => {
  return [moment().add(-7, 'day'), moment().add(-1, 'day')];
  // return [moment('2025-03-01'), moment('2025-03-02')];
};

export default ({ power, buttonPermissions }) => {
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((x) => x.menuCode === 'JieDianJiaGeDuiBiDaoChu'),
    formValue: {}, // 已用表单
    stationName: '',
    expanded: false,
    // form
    openDates: null,
    dates: getDateRange(),
    marketItem: {}, // 交易中心信息
    stationItem: {}, // 交易单元信息
    stationOptions: [], // 交易单元
    pointKey: '96',
    keySub: 'PricesList',
    // result
    loading: true,
    dataSource: null,
    tableData: [],
    tableColumns: [],
    chartOption: null,
  });
  const { theme } = useThemeChange();

  React.useEffect(() => {
    onChangeMarket(power[0], 'search');
  }, []);

  React.useEffect(() => {
    // 格式化渲染数据
    if (state.formValue.marketId === 'PDBLJ' || state.formValue.marketId === 'PXBNX') {
      _onFinish();
    } else {
      const result = fmtDataSource(state.dataSource, state.pointKey, state.keySub);
      setState({ ...result });
    }
  }, [state.keySub]);
  React.useEffect(() => {
    const result = fmtDataSource(
      state.dataSource,
      state.pointKey,
      state.keySub,
      state.formValue.marketId,
    );
    setState({ ...result });
  }, [state.dataSource]);

  React.useEffect(() => {
    // 格式化渲染数据
    setTimeout(() => {
      const { chartOption } = fmtDataSource(
        state.dataSource,
        state.pointKey,
        state.keySub,
        state.formValue.marketId,
      );
      setState({ chartOption });
    }, 1);
  }, [theme]);

  const getAllStation = (data) => _.flattenDeep(data?.map((a) => a?.children));

  const onChangeMarket = (marketItem, type) => {
    // 交易中心改变
    const stationOptions = getAllStation(marketItem?.children || []);
    state.marketItem = marketItem;
    state.stationItem = stationOptions?.[0] || {};
    if (marketItem.marketId === 'PDBLJ' || marketItem.marketId === 'PXBNX') {
      setState({
        keySub: 'adjustAhead',
        pointKey: '96',
        marketItem,
        stationOptions,
        stationItem: state.stationItem,
        formValue: {
          marketId: state.marketItem.value,
        },
      });
    } else {
      setState({
        pointKey: '96',
        keySub: 'PricesList',
        marketItem,
        stationOptions,
        stationItem: state.stationItem,
        formValue: {
          marketId: state.marketItem.value,
        },
      });
    }
    if (type === 'search') {
      _onFinish();
    }
  };

  const _onFinish = async (reset = false) => {
    // 查询
    let formValue = {};
    if (reset === true) {
      formValue = {
        startDate: getDateRange()[0].format('YYYY-MM-DD'),
        endDate: getDateRange()[1].format('YYYY-MM-DD'),
        provinceId: state.marketItem.provinceId,
        marketId: state.marketItem.value,
        stationIds: [state.stationItem.value],
        type: '96',
        stateAdjust:
          state.marketItem.value === 'PDBLJ' || state.marketItem.value === 'PXBNX'
            ? 'adjustAhead'
            : 'PricesList',
      };
    } else {
      formValue = {
        startDate: state.dates[0].format('YYYY-MM-DD'),
        endDate: state.dates[1].format('YYYY-MM-DD'),
        provinceId: state.marketItem.provinceId,
        marketId: state.marketItem.value,
        stationIds: [state.stationItem.value],
        type: state.pointKey === '24' ? '24' : '96',
        stateAdjust: state.keySub,
      };
    }

    const stationName = state.stationItem.label;
    setState({
      formValue,
      stationName,
      loading: true,
    });
    const res = await queryNodePriceDistributionStatistics(formValue);
    let dataSource = {};
    if (formValue.marketId === 'PDBLJ' || formValue.marketId === 'PXBNX') {
      dataSource = res?.data?.data || {};
    } else {
      dataSource = res?.data || {};
    }
    // 修正字段，方便数据切换，（后端多打了个“x”）
    if (formValue.marketId !== 'PDBLJ') {
      dataSource.realtime24PricesList = dataSource.realtime24xPricesList;
      dataSource.realtime24UnadjustedPricesList = dataSource.realtime24xUnadjustedPricesList;
    }
    setState({
      dataSource,
      loading: false,
    });
  };

  const _onReset = () => {
    // 重置
    setState({
      openDates: null,
      dates: getDateRange(),
      pointKey: '96',
      keySub: 'PricesList',
    });
    onChangeMarket(power[0]);
    _onFinish(true);
  };

  const _onExport = () => {
    // 导出
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    const stime = moment(state.formValue.startDate).format('YYYYMMDD');
    const etime = moment(state.formValue.endDate).format('YYYYMMDD');
    const filename = `节点现货价格分布统计-${state.stationName}-${stime}_${etime}`;
    const params = {
      filename,
      header: state.tableColumns.map((x) => x.title),
      data: state.tableData.map((x) => state.tableColumns.map((c) => x[c.dataIndex])),
    };
    export_json_to_excel(params);
  };

  const disabledDate = (v) => {
    // 日期限制一个月范围，不可选未来
    const _dates = state.openDates;
    if (!_dates) return v > moment();
    const tooLate = _dates[0] && v.diff(_dates[0], 'days') > 30;
    const tooEarly = _dates[1] && _dates[1].diff(v, 'days') > 30;
    return v > moment() || !!tooEarly || !!tooLate;
  };
  /** renders */
  return (
    <>
      <div className={styles.rtBtns}>
        <Space size={16}>
          <Button
            style={{ padding: 0 }}
            type="link"
            icon={<UploadOutlined />}
            disabled={state.loading}
            onClick={_onExport}
          >
            导出
          </Button>
          <Button
            style={{ padding: 0 }}
            type="link"
            icon={state.expanded ? <UpSquareOutlined /> : <DownSquareOutlined />}
            onClick={() => setState({ expanded: !state.expanded })}
          >
            {state.expanded ? '收起' : '展开'}
          </Button>
        </Space>
      </div>
      <div className={styles.head}>
        <Space size={16} wrap>
          <Select
            style={{ width: 200 }}
            value={state.marketItem.value}
            options={power}
            optionFilterProp="label"
            showSearch
            showArrow
            onChange={(v, option) => onChangeMarket(option)}
            getPopupContainer={(e) => e.parentNode}
          />
          <DatePicker.RangePicker
            style={{ width: 216 }}
            value={state.openDates || state.dates}
            separator="-"
            format={'YYYYMMDD'}
            disabledDate={disabledDate}
            allowClear={false}
            onChange={(dates) => setState({ dates })}
            onCalendarChange={(openDates) => setState({ openDates })}
            onOpenChange={(open) => setState({ openDates: open ? [null, null] : null })}
            getPopupContainer={(e) => e.parentNode}
          />
          <Select
            style={{ width: 200 }}
            value={state.stationItem.value}
            options={state.stationOptions}
            optionFilterProp="label"
            showSearch
            showArrow
            onChange={(v, stationItem) => setState({ stationItem })}
            getPopupContainer={(e) => e.parentNode}
          />
          <TjSegmented
            value={state.pointKey}
            options={[
              { label: '24', value: '24' },
              { label: '96', value: '96' },
            ]}
            onChange={(pointKey) => setState({ pointKey })}
          />
          <Space size={16}>
            <Button
              style={{ width: 98, height: 32 }}
              type="primary"
              disabled={!state.dates || state.loading}
              onClick={_onFinish}
            >
              查询
            </Button>
            <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
              重置
            </Button>
          </Space>
        </Space>
        {state.formValue.marketId !== 'PDBLN' && (
          <Space size={16} wrap>
            <TjSegmented
              value={state.keySub}
              options={[
                {
                  label: '修正前',
                  value:
                    state.formValue?.marketId === 'PDBLJ' || state.formValue?.marketId === 'PXBNX'
                      ? 'adjustAhead'
                      : 'UnadjustedPricesList',
                },
                {
                  label: '修正后',
                  value:
                    state.formValue?.marketId === 'PDBLJ' || state.formValue?.marketId === 'PXBNX'
                      ? 'adjustAfter'
                      : 'PricesList',
                },
              ]}
              onChange={(keySub) => setState({ keySub })}
            />
          </Space>
        )}
      </div>
      <div className={styles.main}>
        <Spin spinning={state.loading}>
          <TjChart option={state.chartOption} style={{ height: 350 }} />
          {state.expanded && (
            <div className={styles.myTable}>
              <Table
                columns={state.tableColumns}
                dataSource={state.tableData}
                locale={tableLocale}
                rowKey="typename"
                bordered
                scroll={state.tableData.length > 16 ? { x: 600, y: 500 } : { x: 600 }}
                pagination={false}
              />
            </div>
          )}
        </Spin>
      </div>
    </>
  );
};
